#coding=utf-8
import datetime
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required

from forum.models import *

@login_required
def add_thread(request, group):
    if request.method == 'GET':
        return render_to_response('add_thread.html',{'group':group})
    else:
        title = request.POST['title']
        content = request.POST['content']
        
        group = Group.objects.get(slug=group)
        user = request.user
        
        t = Thread()
        t.title = title
        t.group = group
        t.author = user
        t.last_active = datetime.datetime.now()
        t.save()
        
        p = Post()
        p.title = title
        p.content = content
        p.thread = t
        p.author = user
        
        p.save()
        
        '''
        return HttpResponse("<h3>%s</h3>by<b>%s</b><p>%s</p><p>%s</p>"%
                           (title, user.username, group.description, content))
        '''
        return HttpResponseRedirect(reverse('forum.views.list_threads', args=[group.slug,]))
        
def list_threads(request, group):
    #group = Group.objects.get(slug=group)
    threads = Thread.objects.filter(group__slug=group).order_by("created_at").all()
    
    i = 1
    for t in threads:
        t.no = i
        i += 1
    
    return  render_to_response("list_threads.html", {"threads":threads})  

def details_thread(request, group, thread_id):
    thread = Thread.objects.get(id=thread_id)

    first_post = thread.posts[0]
    rest_posts = thread.posts[1:]
    
    thread.hits += 1
    thread.save()
    return render_to_response("details_thread.html", 
                    {"thread":thread, 
                     "first_post":first_post,
                     "rest_posts":rest_posts}
                    )  

def register(request):
    if request.method == "GET":
        return render_to_response('register.html')
    else:
        name = request.POST['username']
        password = request.POST['password']
        password_conf = request.POST['password_conf']
        email = request.POST['email']
        
        if password != password_conf:pass
        
        user = User.objects.create_user(name, email, password)
        
        user.save()
        
        return HttpResponse("%s:register success!"%user.username)

def list_groups(request):
    groups = Group.objects.all()
    return render_to_response("list_groups.html", 
                              {'groups':groups},
                              )
        
